<?php
/**
 * Created by PhpStorm.
 * User: fuguang
 * Date: 2017/10/16
 * Time: 下午4:44
 */

namespace frontend\controllers;
use Yii;
use yii\helpers\Html;
use common\controllers\FrontendController;
use yii\filters\AccessControl;
use frontend\models\LoginForm;
use frontend\models\CallApiForm;
use frontend\models\MiniLoginForm;
use frontend\models\MiniSignupForm;
use frontend\models\User;
use yii\web\NotFoundHttpException;

class MoveController extends FrontendController
{
    public $layout = "main-move";
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index','register','login','logout','update-user','call','sendcode',
                            'check-mobile-exists','send-login-code','call-api','re'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionRe(){
        print_r($_POST);
        print_r($_FILES);

    }
    public function actionIndex(){
        $notice_userid = Yii::$app->request->get("key",0); //需要通知的用户
        $user = Yii::$app->user->identity;

        $notice_userid = Yii::$app->request->get("key",0); //需要通知的用户
        $model = new CallApiForm();
        $notice_user = User::findOne($notice_userid);
        //echo $model->getSmsCode();exit;
        return $this->render('index', [
            'model' => $model,
            'user' => $user,
            'notice_user' => $notice_user
        ]);
    }

    public function actionCall(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new CallApiForm();

        return [
            'title' => "",
            'content' => $this->renderAjax('call', [
                'model' => $model,
            ]),
            'footer' => Html::button('close', ['class' => 'btn btn-default pull-left close', 'data-dismiss' => "modal"]) .
                Html::button('CLOSE', ['class' => 'btn btn-primary', 'type' => "button",'data-dismiss' => "modal"])
        ];

    }

    public function actionSendcode(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $phone = Yii::$app->request->post("phone","");

        return ['ret' => false];

    }


    public function actionCheckMobileExists(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $mobile = Yii::$app->request->post('mobile');

        if( $user = User::findByMobile($mobile) ){
            Yii::$app->getUser()->login($user);
            return ['ret' => true];
        }else{
            /*
            $model = new MiniSignupForm();
            $sign = array('MiniSignupForm' => array('mobile' => $mobile,'username' => $mobile));

            if ($model->load($sign)) {
                if ($user = $model->signup()) {
                    Yii::$app->getUser()->login($user);
                    return ['ret' => true];
                }
            }
            */
            return ['ret' => true];
        }
        return ['ret' => false];
    }

    /**
     * 发送短信验证码
     * doPostBack()会提交到SendLoginCode方法发送登录验证码：
     */
    public function actionSendLoginCode()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $mobile = Yii::$app->request->post('mobile');
        $code = $this->createCode();
        $content = "本次验证码为".$code."，您正在登录xxxx，打死也不告诉别人哦";
        if($this->sendCode($mobile,$content)===true){
            //检查session是否打开
            if(!Yii::$app->session->isActive){
                Yii::$app->session->open();
            }
            //验证码和短信发送时间存储session
            Yii::$app->session->set('login_sms_code',trim($code));
            Yii::$app->session->set('login_sms_time',time());
            return ['ret' => true,'code' => $code];
        }else{
            return ['ret' => false];
        }
    }

    /**
     * 表单提交，调用打电话api实现功能
     * @return array
     */
    public function actionCallApi(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new CallApiForm();
        $post = Yii::$app->request->post();
        $minilogin['CallApiForm'] = $post;

        $load = $model->load($minilogin);

        $code = $minilogin['CallApiForm']['code'];
        $origin_code = $model->getSmsCode();

        if ( $load && $model->validate() && $code == $origin_code) {
            //@todo 进行调用拨打电话api，实现打电话功能,核心功能!
            return ['ret' => true];
        }
        return ['ret' => false];
    }

    public function actionUserinfo(){

        return $this->render('login', [
            'model' => $model,
        ]);
    }

    public function actionUpdateUser(){

    }

    public function actionLogin(){
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new MiniLoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->redirect("index");
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }


    public function actionRegister(){
        $model = new MiniSignupForm();

        if (Yii::$app->request->isPost){
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $data['MiniSignupForm'] = Yii::$app->request->post("postdata");
            if ($model->load($data)) {
                if ($user = $model->signup()) {
                    if (Yii::$app->getUser()->login($user)) {
                        return ['ret' => true,'url' => '/move/index'];
                    }
                }else{
                    foreach ( $model->errors as $item ){
                        $msg = $item[0];
                        break;
                    }
                    return ['ret' => false,'msg' => $msg];
                }
            }else{
                foreach ( $model->errors as $item ){
                    $msg = $item[0];
                    break;
                }
                return ['ret' => false,'msg' => $msg];
            }
        }

        return $this->render('miniregister', [
            'model' => $model,
        ]);
    }

    public function actionForgotpwd(){
        return $this->render('forgotpwd', []);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findUserModel($id),
        ]);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findUserModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}